﻿/********************************************
 * 
 * http://blog.csdn.net/welliu
 * 
 * Email:lgjwell@gmail.com
 * 
 * QQ:147620454
 * 
 *******************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Medicalsystem.MCP.FormDesigner.Common;
using Medicalsystem.MCP.FormDesigner.Ctl;
using Medicalsystem.MCP.FormDesigner.Define;
using Medicalsystem.MCP.FormDesigner.Property;
using Medicalsystem.MCP.FormDesigner.Interface;

namespace Medicalsystem.MCP.FormDesigner
{
    public partial class FormDesigner : DevExpress.XtraEditors.XtraUserControl
    {
        public FormDesigner()
        {
            InitializeComponent();
        }

        private Dictionary<string, ModelDesign> _modelHandlers = null;   //所有模板列表

        private ModelDesign _curModelDesign = null;                      //当前显示模板

        private void Form_ModelDesign_Load(object sender, EventArgs e)
        {
            try
            {
                _modelHandlers = new Dictionary<string, ModelDesign>();

                InitForm();

                //设置控件树点击事件
                this.ctl_ControlTree1.NodeMouseClickEvent += new ctl_ControlTree.ClickHandler(ctl_ControlTree1_NodeMouseClickEvent);

                SingleList.Instance.MessageEvent += new SingleList.messageHandler(Instance_MessageEvent);
                if (_curModelDesign == null) return;

                //设置属性编辑器
                this.Myctl_PropertyGrid.DesignEvent += new ctl_PropertyGrid.DesignHandler(ctl_PropertyGrid1_DesignEvent);

                this.Myctl_PropertyGrid.BringToFront();


            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        public void InitForm()
        {
            string modelid = System.Guid.NewGuid().ToString();
            string modelName = "新建表单";

            this.ctl_TabMenu1.AddTabMenu(modelid, modelName);
            this.ctl_TabMenu1_TabChangedEvent(null, new ModelShowEventArgs(modelid, modelName));
        }

        public Boolean EnableMenu
        {
            get { return menuStrip1.Visible; }
            set { menuStrip1.Visible = value; }

        }

        #region 菜单功能
        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Parent != null && this.Parent is Form)
            {

                (this.Parent as Form).Close();

            }
        }

        private void 新建表单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Form_AddModel F = new Form_AddModel();
                F.ShowDialog();

                if (F.DialogResult == DialogResult.OK)
                {
                    string modelid = System.Guid.NewGuid().ToString();

                    this.ctl_TabMenu1.AddTabMenu(modelid, F.FormName);
                    this.ctl_TabMenu1_TabChangedEvent(null, new ModelShowEventArgs(modelid, F.FormName));
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }
        private void 从现有模板添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(this.openFileDialog1.FileName);

                    string shorName = GetShortName(this.openFileDialog1.FileName);
                    string modelid = System.Guid.NewGuid().ToString();

                    this.ctl_TabMenu1.AddTabMenu(modelid, shorName);
                    this.ctl_TabMenu1_TabChangedEvent(null, new ModelShowEventArgs(modelid, shorName));

                    _curModelDesign.FileName = this.openFileDialog1.FileName;
                    XML.XMLToModel(doc, _curModelDesign);

                    ShowComContainer();

                    PropertyGridAndMenuBindReset();
                    this.StatusText.Text = "完成";
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this._curModelDesign.FileName))
                {
                    另存为XMLToolStripMenuItem_Click(sender, e);
                }
                else
                {
                    this._curModelDesign.CtrlKeyDown = false;

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(XML.ModelToXML(_curModelDesign));

                    //保存XML
                    XmlTextWriter writer = new XmlTextWriter(_curModelDesign.FileName, Encoding.Default);
                    writer.Formatting = Formatting.Indented;
                    doc.Save(writer);
                    writer.Close();

                    this.StatusText.Text = "保存成功";
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        private void 另存为XMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog1.FileName = string.Format("{0}.xml", this.ctl_TabMenu1.SelectedTabText);
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    this._curModelDesign.CtrlKeyDown = false;

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(XML.ModelToXML(_curModelDesign));

                    //保存XML
                    XmlTextWriter writer = new XmlTextWriter(saveFileDialog1.FileName, Encoding.Default);
                    writer.Formatting = Formatting.Indented;
                    doc.Save(writer);

                    writer.Close();

                    this._curModelDesign.FileName = saveFileDialog1.FileName;
                    this.ctl_TabMenu1.SelectedTabText = GetShortName(saveFileDialog1.FileName);
                }

            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        private void 导入模板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(this.openFileDialog1.FileName);

                    //清除信息 
                    this.StatusText.Text = "正在导入XML...";

                    this._curModelDesign.Reset();
                    this.Myctl_PropertyGrid.Clear();

                    _curModelDesign.FileName = this.openFileDialog1.FileName;
                    XML.XMLToModel(doc, _curModelDesign);

                    ShowComContainer();

                    PropertyGridAndMenuBindReset();

                    this.ctl_TabMenu1.SelectedTabText = GetShortName(this.openFileDialog1.FileName);
                    this.StatusText.Text = "完成";
                }
            }
            catch (Exception ex)
            {
                this.toolStrip1.Text = ex.Message;
                TryCustomException.TransactException(ex);
            }
        }

        private void 全部保存LToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }



        private void 撤销删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 复制模板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SingleList.Instance.CopyPaste.Copy(_curModelDesign);
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void 粘贴模板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (SingleList.Instance.CopyPaste.CopyType == ECopyType.CopyModel)
                {
                    this._curModelDesign.Reset();
                    this.Myctl_PropertyGrid.Clear();
                    SingleList.Instance.CopyPaste.Paste(_curModelDesign);
                    PropertyGridAndMenuBindReset();
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (_curModelDesign.SelectList.Count > 0)
                {
                    SingleList.Instance.CopyPaste.Cut(_curModelDesign.SelectList);
                    删除DToolStripMenuItem_Click(null, null);
                    this.StatusText.Text = "复制到了剪贴板";
                    this._curModelDesign.CtrlKeyDown = false; //手工设置 因为删除了控件 焦点转移 键盘按键事件 丢失
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void 复制CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (_curModelDesign.SelectList.Count > 0)
                {
                    SingleList.Instance.CopyPaste.Copy(_curModelDesign.SelectList);
                    this.StatusText.Text = string.Format("复制了 {0} 个控件", _curModelDesign.SelectList.Count.ToString());
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void 粘贴PToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (SingleList.Instance.CopyPaste.CopyType == ECopyType.CopyControls || SingleList.Instance.CopyPaste.CopyType == ECopyType.CutControls)
                {
                    List<CtrlMngDesign> ctrls;

                    if (_curModelDesign.CtrlMngDesignFocused == null)
                    {
                        //粘贴到模板
                        ctrls = SingleList.Instance.CopyPaste.Paste(_curModelDesign.CtrlUIContainerHandler, _curModelDesign);
                    }
                    else if (_curModelDesign.CtrlMngDesignFocused.Owner is ICtrlContainer)
                    {
                        //粘贴到焦点控件子容器中
                        ctrls = SingleList.Instance.CopyPaste.Paste(_curModelDesign.CtrlMngDesignFocused.ChildContainerFocused, _curModelDesign);
                    }
                    else
                    {
                        //粘贴到焦点控件父容器中
                        ctrls = SingleList.Instance.CopyPaste.Paste(_curModelDesign.CtrlMngDesignFocused.ParentContainer, _curModelDesign);
                    }

                    PropertyGridAndMenuBindReset();

                    if (ctrls.Count > 0)
                    {
                        foreach (CtrlMngDesign ctrl in ctrls)
                        {
                            _curModelDesign.SelectListAppend(ctrl);
                            ctrl.BringToFront();
                        }

                        //这里将拷贝的控件按以前的层叠顺序置于最上层
                        for (int i = ctrls.Count - 1; i >= 0; i--)
                        {
                            ctrls[i].BringToFront();
                        }

                        this._curModelDesign.SelectListAppendEnd(false);
                        _curModelDesign.CtrlMngDesignFocused.ParentContainer.Container.Refresh();
                    }
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void 删除DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DeleteControl();
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void 全部删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this._curModelDesign.Reset();
                this.Myctl_PropertyGrid.Clear();
                this.Myctl_PropertyGrid.Add(this._curModelDesign.Owner);
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void 全选AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (_curModelDesign.CtrlMngDesignFocused == null)
                {
                    //选取模板中的控件
                    foreach (CtrlMngDesign ctrl in this._curModelDesign.CtrlUIContainerHandler.Controls)
                    {
                        this._curModelDesign.SelectListAppend(ctrl);
                    }
                }
                else
                {
                    //选取焦点控件所属容器的控件
                    foreach (CtrlMngDesign ctrl in this._curModelDesign.CtrlMngDesignFocused.ParentContainer.Controls)
                    {
                        this._curModelDesign.SelectListAppend(ctrl);
                    }
                }

                this._curModelDesign.SelectListAppendEnd(false);
                this._curModelDesign.Refresh();
            }
            catch (Exception err)
            {
                this.StatusText.Text = err.Message;
            }
        }

        private void 焦点置于顶层toolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.焦点置于顶层toolStripMenuItem.Checked = !this.焦点置于顶层toolStripMenuItem.Checked;
        }

        private void 移动锁定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.移动锁定ToolStripMenuItem.Checked = !this.移动锁定ToolStripMenuItem.Checked;
            SingleList.Instance.MoveLock = this.移动锁定ToolStripMenuItem.Checked;
        }



        #endregion

        #region 工具栏功能

        private void toolStripBtn_Save_Click(object sender, EventArgs e)
        {

            保存SToolStripMenuItem_Click(null, null);
        }

        private void toolStripBtn_Cut_Click(object sender, EventArgs e)
        {
            剪切ToolStripMenuItem_Click(null, null);
        }

        private void toolStripBtn_Copy_Click(object sender, EventArgs e)
        {
            复制CToolStripMenuItem_Click(null, null);
        }

        private void toolStripBtn_Paste_Click(object sender, EventArgs e)
        {
            粘贴PToolStripMenuItem_Click(null, null);
        }

        private void toolStripBtn_Delete_Click(object sender, EventArgs e)
        {
            删除DToolStripMenuItem_Click(null, null);
        }

        private void toolStripBtn_Undo_Click(object sender, EventArgs e)
        {

        }

        private void toolStripBtn_Run_Click(object sender, EventArgs e)
        {
            try
            {
                DevExpress.XtraEditors.XtraForm F = new FromRun();
                Model M = new Model(_curModelDesign.ModelID, F);
                XMLConvert.XMLConvertToModel(XML.ModelToXML(_curModelDesign), M);
                F.StartPosition = FormStartPosition.CenterScreen;
                F.Show();
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }

        }

        private void toolStripBtn_Left_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("left");
        }

        private void toolStripBtn_CenterH_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("centerh");
        }

        private void toolStripBtn_Right_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("right");
        }

        private void toolStripBtn_Top_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("top");
        }

        private void toolStripBtn_CenterV_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("centerv");
        }

        private void toolStripBtn_Bottom_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("bottom");
        }

        private void toolStripBtn_Width_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("width");
        }

        private void toolStripBtn_Height_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("height");
        }

        private void toolStripBtn_Size_Click(object sender, EventArgs e)
        {
            toolStripBtnEvent("size");
        }

        private void toolStripBtn_EqualH_Click(object sender, EventArgs e)
        {
            try
            {
                if ((this._curModelDesign.CtrlMngDesignFocused != null) && (this._curModelDesign.CtrlMngDesignFocused.Owner is ICtrlUI) && (this._curModelDesign.SelectList.Count >= 3))
                {
                    List<CtrlMngDesign> CtrlMngDesignList = new List<CtrlMngDesign>();
                    foreach (CtrlMngDesign ctrl in this._curModelDesign.SelectList)
                    {
                        if (ctrl.Owner is ICtrlUI)
                        {
                            CtrlMngDesignList.Add(ctrl);
                        }
                    }

                    if (CtrlMngDesignList.Count < 3) return;

                    CtrlMngDesign[] ctrls = CtrlMngDesignList.ToArray();
                    CtrlMngDesign ctrlTemp = null;

                    for (int i = 0; i < ctrls.Length - 1; i++)
                    {
                        for (int j = i + 1; j < ctrls.Length; j++)
                        {
                            if (ctrls[j].Owner.Left < ctrls[i].Owner.Left)
                            {
                                ctrlTemp = ctrls[i];
                                ctrls[i] = ctrls[j];
                                ctrls[j] = ctrlTemp;
                            }
                        }
                    }

                    //控件最大间距
                    int width = ctrls[ctrls.Length - 1].Owner.Left - ctrls[0].Owner.Left - ctrls[0].Owner.Width;
                    int allWidth = 0; //中间控件高度

                    for (int i = 1; i < ctrls.Length - 1; i++)
                    {
                        allWidth += ctrls[i].Owner.Width;
                    }

                    int cellWidth = -1;

                    if (allWidth < width)
                    {
                        cellWidth = (width - allWidth) / (ctrls.Length - 1);
                    }

                    int curLeft = ctrls[0].Owner.Left + ctrls[0].Owner.Width + cellWidth;
                    for (int i = 1; i < ctrls.Length; i++)
                    {
                        ctrls[i].Owner.Left = curLeft;
                        curLeft += ctrls[i].Owner.Width + cellWidth;
                        //ctrls[i].UISKnob.SetUISizeDotsPosition();
                        //ctrls[i].UISKnob.SetUIMoveDotPosition();
                    }

                    this._curModelDesign.CtrlMngDesignFocused.ParentContainer.Container.Refresh();
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void toolStripBtn_EqualV_Click(object sender, EventArgs e)
        {
            try
            {
                //思路：
                //1.建立一个数组根据Top值从小到大排列
                //2.计算Top值最大最小之间的距离 as a
                //3.计算中间控件的总高度 as b
                //4.比较 a 与 b 的大小
                //5.如果 b>=a 控件顺序往下排列
                //6.如果 b<a 计算控件平均距离

                if ((this._curModelDesign.CtrlMngDesignFocused != null) && (this._curModelDesign.CtrlMngDesignFocused.Owner is ICtrlUI) && (this._curModelDesign.SelectList.Count >= 3))
                {
                    List<CtrlMngDesign> CtrlMngDesignList = new List<CtrlMngDesign>();
                    foreach (CtrlMngDesign ctrl in this._curModelDesign.SelectList)
                    {
                        if (ctrl.Owner is ICtrlUI)
                        {
                            CtrlMngDesignList.Add(ctrl);
                        }
                    }

                    if (CtrlMngDesignList.Count < 3) return;

                    CtrlMngDesign[] ctrls = CtrlMngDesignList.ToArray();
                    CtrlMngDesign ctrlTemp = null;

                    for (int i = 0; i < ctrls.Length - 1; i++)
                    {
                        for (int j = i + 1; j < ctrls.Length; j++)
                        {
                            if (ctrls[j].Owner.Top < ctrls[i].Owner.Top)
                            {
                                ctrlTemp = ctrls[i];
                                ctrls[i] = ctrls[j];
                                ctrls[j] = ctrlTemp;
                            }
                        }
                    }

                    //控件最大间距
                    int height = ctrls[ctrls.Length - 1].Owner.Top - ctrls[0].Owner.Top - ctrls[0].Owner.Height;
                    int allHeight = 0; //中间控件高度

                    for (int i = 1; i < ctrls.Length - 1; i++)
                    {
                        allHeight += ctrls[i].Owner.Height;
                    }

                    int cellHeight = -1;

                    if (allHeight < height)
                    {
                        cellHeight = (height - allHeight) / (ctrls.Length - 1);
                    }

                    int curTop = ctrls[0].Owner.Top + ctrls[0].Owner.Height + cellHeight;
                    for (int i = 1; i < ctrls.Length; i++)
                    {
                        ctrls[i].Owner.Top = curTop;
                        curTop += ctrls[i].Owner.Height + cellHeight;
                    }

                    this._curModelDesign.CtrlMngDesignFocused.ParentContainer.Container.Refresh();
                }//end if
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void toolStripBtn_BringToFrontHS_Click(object sender, EventArgs e)
        {
            try
            {
                //只作用于焦点控件

                if ((this._curModelDesign.CtrlMngDesignFocused != null) && (this._curModelDesign.CtrlMngDesignFocused.Owner is ICtrlUI))
                {
                    this._curModelDesign.CtrlMngDesignFocused.BringToFront();

                    this._curModelDesign.CtrlMngDesignFocused.BackLock = false;
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private void toolStripBtn_SendToBackHS_Click(object sender, EventArgs e)
        {
            try
            {
                //只作用于焦点控件

                if ((this._curModelDesign.CtrlMngDesignFocused != null) && (this._curModelDesign.CtrlMngDesignFocused.Owner is ICtrlUI))
                {
                    this._curModelDesign.CtrlMngDesignFocused.SendToBack();

                    this._curModelDesign.CtrlMngDesignFocused.BackLock = true;
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        #endregion

        #region 其他功能

        private void pictureBox_Property_MouseHover(object sender, EventArgs e)
        {
            try
            {
                this.StatusText.Text = "F4 查看焦点控件属性";
                ProrertyGridSet();
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        private void Form_ModelDesign_FormClosing(object sender, FormClosingEventArgs e)
        {
            SingleList.Instance.Dispose();
        }

        #endregion

        #region 私有方法


        private void ShowComContainer()
        {
            if (this._curModelDesign.CtrlComContainerHandler.Controls.Count == 0)
            {
                this._curModelDesign.ModeDesignObject.Container_ComVisible = false;
            }
            else
            {
                this._curModelDesign.ModeDesignObject.Container_ComVisible = true;
            }
        }

        /// <summary>
        /// 删除选取控件
        /// </summary>
        private void DeleteControl()
        {
            //删除选取的控件及其子控件
            //删除引用关系 -- 1、容器引用 2、模板引用 3、选取引用
            //重设属性关系
            if (_curModelDesign.CtrlMngDesignFocused == null)
            {
                return;

            }
            ContainerHandler container = _curModelDesign.CtrlMngDesignFocused.ParentContainer;
            _curModelDesign.CtrlMngDesignFocused = null;
            this.StatusText.Text = string.Format("删除了 {0} 个控件", this._curModelDesign.SelectList.Count.ToString());

            container.Container.SuspendLayout();

            foreach (CtrlMngDesign ctrlDes in this._curModelDesign.SelectList)
            {
                //this._curModelDesign.Controls.Ctrls.Remove(ctrlDes);
                //container.Controls.Remove(ctrlDes);
                //ctrlDes.Dispose();

                this._curModelDesign.RemoveControl(ctrlDes);
            }
            this._curModelDesign.SelectList.Clear();

            container.Container.ResumeLayout(false);

            PropertyGridAndMenuBindReset();

            container.Container.Refresh();

            ShowComContainer();
        }

        /// <summary>
        /// 对属性显示框的设置
        /// </summary>
        private void ProrertyGridSet()
        {
            this.Myctl_PropertyGrid.VisibleCustom = true;
            this.Myctl_PropertyGrid.Focus();
        }

        /// <summary>
        /// 模板显示
        /// </summary>
        private void ModelShow(string modelID, string modelName)
        {
            if (this._modelHandlers.ContainsKey(modelID))
            {
                this._modelHandlers.TryGetValue(modelID, out _curModelDesign);
            }
            else
            {
                DevExpress.XtraEditors.XtraForm F = new FromRun();
                F.Name = modelName;
                F.Text = modelName;
                F.ContextMenuStrip = this.contextMenuStrip1;
                F.Dock = DockStyle.Fill;
                ctl_ModelDesignObject mdo = new ctl_ModelDesignObject(modelID, F);
                mdo.Dock = DockStyle.Fill;
                this.panel_Container.Controls.Add(mdo);

                ModelDesign CMH = new ModelDesign(mdo);

                _modelHandlers.Add(modelID, CMH);

                _curModelDesign = CMH;
            }

            if (this._curModelDesign != null)
            {
                this._curModelDesign.ModeDesignObject.Visible = true;
            }
        }

        /// <summary>
        /// 工具栏控件调整
        /// </summary>
        /// <param name="flag"></param>
        private void toolStripBtnEvent(string flag)
        {
            try
            {
                if ((this._curModelDesign.CtrlMngDesignFocused != null) && (this._curModelDesign.SelectList.Count > 0) && (this._curModelDesign.CtrlMngDesignFocused.Owner is ICtrlUI))
                {
                    System.Windows.Forms.Control C = this._curModelDesign.CtrlMngDesignFocused.Owner;

                    foreach (CtrlMngDesign CtrlMngDesign in this._curModelDesign.SelectList)
                    {
                        //if (CtrlMngDesign.Container == this._curModelDesign.CtrlMngDesignFocused.Container)
                        //{
                        switch (flag.ToLower())
                        {
                            case "left":
                                CtrlMngDesign.Owner.Left = C.Left;
                                break;
                            case "right":
                                CtrlMngDesign.Owner.Left = C.Left + C.Width - CtrlMngDesign.Owner.Width;
                                break;
                            case "centerh":
                                CtrlMngDesign.Owner.Left = C.Left + C.Width / 2 - CtrlMngDesign.Owner.Width / 2;
                                break;
                            case "top":
                                CtrlMngDesign.Owner.Top = C.Top;
                                break;
                            case "bottom":
                                CtrlMngDesign.Owner.Top = C.Top + C.Height - CtrlMngDesign.Owner.Height;
                                break;
                            case "centerv":
                                CtrlMngDesign.Owner.Top = C.Top + C.Height / 2 - CtrlMngDesign.Owner.Height / 2;
                                break;
                            case "width":
                                CtrlMngDesign.Owner.Width = C.Width;
                                break;
                            case "height":
                                CtrlMngDesign.Owner.Height = C.Height;
                                break;
                            case "size":
                                CtrlMngDesign.Owner.Width = C.Width;
                                CtrlMngDesign.Owner.Height = C.Height;
                                break;
                            default:
                                break;
                        }
                    }

                    this._curModelDesign.CtrlMngDesignFocused.ParentContainer.Container.Refresh();
                }
            }
            catch (Exception ex)
            {
                this.StatusText.Text = ex.Message;
            }
        }

        private string GetShortName(string fullName)
        {
            string shorName = fullName.Substring(fullName.LastIndexOf('\\') + 1, fullName.LastIndexOf('.') - fullName.LastIndexOf('\\') - 1);

            return shorName;
        }

        #endregion

        #region 接收控件处理消息

        /// <summary>
        /// 接收控件处理消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Instance_MessageEvent(object sender, MessageType e)
        {
            try
            {
                switch (e)
                {
                    case MessageType.CreateControl:
                        CreateControl((CtrlMngDesign)sender);
                        break;
                    case MessageType.ControlFocus:
                        Control_GotFocus(sender);
                        break;
                    case MessageType.ModelFocus:
                        Model_GotFocus(sender);
                        break;
                    case MessageType.KeyEvent:
                        CtrlMngDesign_KeyKnobEvent(sender);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        private void CreateControl(CtrlMngDesign CtrlMngDesign)
        {

            CtrlMngDesign.Owner.ContextMenuStrip = this.contextMenuStrip1;

            //控件新建状态下 执行下面操作
            if (!string.IsNullOrEmpty(SingleList.Instance.ControlName))
            {
                this.Myctl_PropertyGrid.Add(CtrlMngDesign.Owner);

                //设置为选取项
                this._curModelDesign.SelectListAdd(CtrlMngDesign);
                CtrlMngDesign.BringToFront();

                ShowComContainer();

                if (this.toolStripComboBox_NewType.Text.ToLower().Equals("single"))
                {
                    SingleList.Instance.ControlName = string.Empty;
                }
            }
        }

        private void Model_GotFocus(object sender)
        {
            try
            {
                if (sender != null)
                {
                    this.Myctl_PropertyGrid.SelectedForm = new GetModelProperty(_curModelDesign);
                    (sender as System.Windows.Forms.Control).Focus();
                }
                else
                {
                    this.Myctl_PropertyGrid.SelectedObject(null);
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 控件焦点时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Control_GotFocus(object sender)
        {
            try
            {
                if (sender != null)
                {
                    CtrlMngDesign ctrlMngDesign = (CtrlMngDesign)sender;

                    this.Myctl_PropertyGrid.SelectedObject(ctrlMngDesign.Owner);

                    if (!ctrlMngDesign.BackLock && this.焦点置于顶层toolStripMenuItem.Checked)
                    {
                        ctrlMngDesign.BringToFront();
                    }

                    ctrlMngDesign.Owner.Focus();
                }
                else
                {
                    this.Myctl_PropertyGrid.SelectedObject(null);
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 处理控件和模板的键盘响应
        /// 
        /// 在控件焦点上引发键盘事件时 同时会引发模板键盘事件
        /// 所以 当两边都有相同事件时 控件就不执行事件
        /// </summary>
        private void CtrlMngDesign_KeyKnobEvent(object sender)
        {
            try
            {
                switch ((sender as KeyEventArgs).KeyCode)
                {
                    case Keys.F4:
                        ProrertyGridSet();
                        break;
                    case Keys.F5:
                        toolStripBtn_Run_Click(null, null);
                        break;
                    case Keys.Delete:
                        DeleteControl();
                        break;
                    case Keys.A:
                        if (this._curModelDesign.CtrlKeyDown)
                        {
                            全选AToolStripMenuItem_Click(null, null);
                        }
                        break;
                    case Keys.C:
                        if (this._curModelDesign.CtrlKeyDown)
                        {
                            复制CToolStripMenuItem_Click(null, null);
                        }
                        break;
                    case Keys.V:
                        if (this._curModelDesign.CtrlKeyDown)
                        {
                            粘贴PToolStripMenuItem_Click(null, null);
                        }
                        break;
                    case Keys.X:
                        if (this._curModelDesign.CtrlKeyDown)
                        {
                            剪切ToolStripMenuItem_Click(null, null);
                        }
                        break;
                    case Keys.Z:
                        撤销删除ToolStripMenuItem_Click(null, null);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        #endregion

        #region 外部委托调用方法

        /// <summary>
        /// 添加或删除控件后
        /// 重新初始化属性控件的下拉列表
        /// </summary>
        private void PropertyGridAndMenuBindReset()
        {
            try
            {
                this.Myctl_PropertyGrid.Clear();
                this.Myctl_PropertyGrid.Add(this._curModelDesign.Owner);

                foreach (CtrlMngDesign CH in this._curModelDesign.Controls.Ctrls)
                {
                    this.Myctl_PropertyGrid.Add(CH.Owner);
                    CH.Owner.ContextMenuStrip = this.contextMenuStrip1;
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }


        /// <summary>
        /// 控件点击
        /// </summary>
        private void ctl_ControlTree1_NodeMouseClickEvent(string ctrlName, string assName)
        {
            this.StatusText.Text = "就绪";
            SingleList.Instance.ControlName = ctrlName;
            SingleList.Instance.AssemblyName = assName;
        }

        /// <summary>
        /// 属性显示与控件焦点的关联
        /// </summary>
        private void ctl_PropertyGrid1_DesignEvent(System.Windows.Forms.Control control)
        {
            try
            {
                if (control is Form)
                {
                    this._curModelDesign.SelectListClear();
                    this.Myctl_PropertyGrid.SelectedForm = new GetModelProperty(_curModelDesign);
                    control.Focus();
                }
                else
                {
                    CtrlMngDesign CtrlMngDesign = (CtrlMngDesign)this._curModelDesign.Controls.Ctrls.Find(delegate(CtrlMng ch) { return (ch as CtrlMngDesign).Owner == control; });
                    if (CtrlMngDesign != null)
                    {
                        //设置为选取项
                        this._curModelDesign.SelectListAdd(CtrlMngDesign);
                        CtrlMngDesign.ParentContainer.Container.Refresh();
                    }
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }


        /// <summary>
        /// 选项卡改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctl_TabMenu1_TabChangedEvent(object sender, ModelShowEventArgs e)
        {
            try
            {
                if (this._curModelDesign != null)
                {
                    this._curModelDesign.SelectListClear();
                    this._curModelDesign.ModeDesignObject.Visible = false;
                }

                SingleList.Instance.Reset();

                ModelShow(e.ModelID, e.ModelName);

                this.Myctl_PropertyGrid.SelectedObject(null);
                PropertyGridAndMenuBindReset();
                ShowComContainer();

                if (this._curModelDesign != null)
                {
                    this._curModelDesign.Refresh();
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        #region 右键菜单

        private void 删除MenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            删除DToolStripMenuItem_Click(null, null);
        }

        private void 剪贴MenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            剪切ToolStripMenuItem_Click(null, null);
        }

        private void 复制MenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            复制CToolStripMenuItem_Click(null, null);
        }

        private void 粘贴MenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            粘贴PToolStripMenuItem_Click(null, null);
        }

        private void 全选MenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            全选AToolStripMenuItem_Click(null, null);
        }

        private void 属性MenuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProrertyGridSet();
        }

        #endregion

        /// <summary>
        /// 打开模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripBtn_Open_Click(object sender, EventArgs e)
        {
            导入模板ToolStripMenuItem_Click(sender, e);
        }



        #endregion



    }
}
